#include "../inc/client.h"


int mode = 0;           // 记录当前模式
int connect_flag = 0;   // 连接标志


// 定义全局变量来存储时、分、秒
int hours = 0;
int minutes = 0;
int seconds = 0;

int confirm_send = 0;   // 确认发送标识
int recv_flag = 0;      // 接收标志 1 表示正在接收消息
const char *input_text; // 输入文本

int private_msg_cont = 0; // 当前私聊消息数量
int group_msg_cont = 0;   // 当前群聊消息数量


// IP链表初始化
IpList InitIpList()
{
    IpList head = (IpList)malloc(sizeof(IpNode));
    if (head == (IpList)NULL)
    {
        perror("malloc ...");
        return (IpList)NULL;
    }
    memset(head, 0, sizeof(IpNode));
    head->next = NULL;
    return head;
}
// 添加IP到链表
void AddIpToIpList(IpList *head, const char *ip)
{
    if (FindIpInList(*head, ip) == NULL) // 检查IP是否已经存在
    {
        IpNode *newNode = (IpNode *)malloc(sizeof(IpNode));
        if (newNode == NULL)
        {
            perror("malloc failed");
            return;
        }
        strncpy(newNode->ip, ip, IP_LEN);
        newNode->next = *head;
        *head = newNode;
    }
}
// 遍历IP链表
void PrintIpList(IpList head)
{
    IpNode *current = head;
    while (current->next != NULL)
    {
        printf("IP: %s\n", current->ip);
        current = current->next;
    }
}
// 释放IP链表
void FreeIpList(IpList *head)
{
    IpNode *current = *head;
    IpNode *temp;
    while (current != NULL)
    {
        temp = current;
        current = current->next;
        free(temp);
    }
    *head = NULL;
}
// 在链表中查找IP地址
IpNode *FindIpInList(IpList head, const char *ip)
{
    IpNode *current = head;
    while (current != NULL)
    {
        if (strcmp(current->ip, ip) == 0)
        {
            return current; // 找到IP，返回节点
        }
        current = current->next;
    }
    return NULL; // 没有找到IP
}

// 发送消息
void *Send(void *arg)
{
    pthread_detach(pthread_self()); // 设置线程分离
    int *cli_fd = (int *)arg;
    char msg[MSG_MAX_LEN];

    while (!EXIT_SEND)
    {
        input_text = lv_textarea_get_text(text_ta); // 获取输入文本
        if (strlen(input_text) > 0 && confirm_send == 1)
        {
            // 将输入文本复制到消息缓冲区
            memset(msg, 0, MSG_MAX_LEN);
            strncpy(msg, input_text, MSG_MAX_LEN - 1);

            int msg_len = strlen(msg) + 1;
            if (chat_mode == 1 && msg_len > 1) // 群聊模式
            {
                if (write(*cli_fd, msg, msg_len) == -1)
                {
                    perror("write ...");
                    pthread_exit((void *)-1);
                }
                printf("成功发送\n");
                // 显示群聊信息和头像
                show_group_msg(msg);
            }
            else if (chat_mode == 2 && msg_len > 1) // 私聊模式
            {
                char private_msg[MSG_MAX_LEN + 30];
                memset(private_msg, 0, MSG_MAX_LEN + 30);
                snprintf(private_msg, sizeof(private_msg), "P_Chat:%s:%s", target_ip, msg);
                if (write(*cli_fd, private_msg, strlen(private_msg)) + 1 == -1)
                {
                    perror("write ...");
                    pthread_exit((void *)-1);
                }
                printf("\n成功发送\n");
                // 显示私聊信息和头像
                show_private_msg(msg);
            }
            // 清空文本区域
            lv_textarea_set_text(text_ta, "");

            confirm_send = 0;
        }
    }
    EXIT_SEND = 1;
    chat_mode = 0;

    pthread_exit((void *)0);
}

// 群聊任务
bool GroupChat_Task(int *cli_fd)
{
    printf("\n进入群聊模式\n");
    int client_fd = *cli_fd;

    if (write(client_fd, WE_CHAT, strlen(WE_CHAT)) == -1)
    {
        perror("write ...");
        return false;
    }

    // 创建线程,用于发消息
    pthread_t send_id;
    if (pthread_create(&send_id, NULL, Send, (void *)&client_fd) != 0)
    {
        perror("pthread_create ...");
        return -1;
    }

    while (1)
    {
        if (EXIT_SEND == 1)
        {
            if (write(client_fd, EXIT_MASK, strlen(EXIT_MASK)) == -1)
            {
                perror("write ...");
            }
            printf("\n退出群聊模式\n");
            if (pthread_cancel(send_id) != 0) // 取消发送消息的线程
            {
                perror("pthread_cancel ... ");
                EXIT_SEND = 0; // 重置标志位
                mode = 0;
                return -1;
            }
            EXIT_SEND = 0; // 重置标志位
            mode = 0;
            break;
        }
    }
    mode = 0;
    return true;
}

// 私聊任务
bool PrivateChat_Task(int *cli_fd)
{
    printf("\n进入私聊模式\n");
    int client_fd = *cli_fd;

    // 创建线程,用于发消息
    pthread_t send_id;
    if (pthread_create(&send_id, NULL, Send, (void *)&client_fd) != 0)
    {
        perror("pthread_create ...");
        return -1;
    }

    while (1)
    {
        if (EXIT_SEND == 1)
        {
            if (write(client_fd, EXIT_MASK, strlen(EXIT_MASK)) == -1)
            {
                perror("write ...");
            }
            printf("\n退出私聊模式\n");
            if (pthread_cancel(send_id) != 0) // 取消发送消息的线程
            {
                perror("pthread_cancel ... ");
                EXIT_SEND = 0; // 重置标志位
                mode = 0;
                return -1;
            }
            EXIT_SEND = 0; // 重置标志位
            break;
        }
    }
    mode = 0;
    return true;
}

// 接收服务器消息
void *Recv_server(void *arg)
{
    pthread_detach(pthread_self()); // 设置线程分离

    int *cli_fd = (int *)arg;
    char msg[MSG_MAX_LEN];

    IpList ipList = InitIpList(); // 初始化IP链表

    while (EXIT_CLIENT)
    {
        memset(msg, 0, MSG_MAX_LEN);

        int ret = read(*cli_fd, msg, sizeof(msg) - 1); // 读取的数据不包括 null 终止符
        if (ret == -1)
        {
            perror("read ...");
            FreeIpList(&ipList);
            pthread_exit((void *)-1);
        }
        if (ret == 0 || strcmp(msg, EXIT_MASK) == 0)
        {
            printf("\n服务器已关闭\n");
            break;
        }
        // 确保字符串终止
        msg[ret] = '\0';
        // printf("\n收到服务器消息：\n%s\n", msg); // 测试用

        if (strstr(msg, "IP_LIST:") != 0) // 如果是在线IP列表
        {
            char *token = strtok(msg + 8, ","); // 分割消息头
            if (token == NULL)
            {
                continue;
            }

            // 清空链表并重新添加
            FreeIpList(&ipList);
            ipList = InitIpList();

            if (strstr(msg, "No") != 0) // 没有其他在线用户
            {
                prompt_msgbox("没有其他在线用户");
                ipList == NULL;
                update_online_clients(ipList);
                continue;
            }

            while (token != NULL)
            {
                // 确保添加的 IP 不为空
                if (strlen(token) > 0)
                {
                    AddIpToIpList(&ipList, token); // 添加IP到链表
                }
                token = strtok(NULL, ",");
            }

            PrintIpList(ipList);
            // 更新聊天列表
            update_online_clients(ipList);
        }
        else if (strstr(msg, "WEATHER:") != 0 && (strlen(msg) > 9)) // 如果是天气信息
        {
            char *weather_msg = msg + 8;
            weather_label(weather_msg);
            printf("天气信息：%s\n", weather_msg);
        }
        else if (strstr(msg, "GROUP_C:") != 0) // 如果消息是群聊信息
        {
            char *group_msg = msg + 8;

            recv_flag = 1;
            show_group_msg(group_msg);

            // 未进入对应聊天窗口则隐藏
            if (group_chat_canvas != NULL && chat_mode != 1)
                lv_obj_add_flag(group_chat_canvas, LV_OBJ_FLAG_HIDDEN);

            printf("\n收到群聊信息：%s\n", group_msg);
        }
        else if (strstr(msg, "PRIVATE_MSG:") != 0) // 如果消息是私聊信息
        {
            char *recv_msg = msg + 12;
            if (strstr(msg, "不在线") != 0)
            {
                prompt_msgbox("对方不在线");
            }
            else
            {
                // 对方将IP分隔出来
                char ip_str[IP_LEN];
                sscanf(recv_msg, "%15[^,]", ip_str);
                // 将主要消息分隔出来
                char *private_msg = recv_msg + 19;
                printf("对方的IP：%s\n", ip_str);

                // 显示私聊信息窗口
                recv_flag = 1;
                show_private_msg(private_msg);

                // 未进入对应聊天窗口则隐藏
                if (private_chat_canvas != NULL && chat_mode != 2)
                    lv_obj_add_flag(private_chat_canvas, LV_OBJ_FLAG_HIDDEN);
            }

            printf("\n收到私聊信息：%s\n", recv_msg);
        }
        else if (strstr(msg, "TIME:") != 0) // 如果是时间信息
        {
            char *time_msg = msg + 5;
            show_time(time_msg);
            printf("\n当前时间：%s\n", time_msg);
        }
    }
    close(*cli_fd);
    FreeIpList(&ipList); // 释放链表
    EXIT_CLIENT = 0;
    pthread_exit((void *)0);
}

// 显示时间
void show_time(char *time_msg)
{
    char date[256];
    char time[256];

    // 使用 sscanf 从 time_msg 中提取日期与时间信息
    int ret = sscanf(time_msg, "%255s %255s", date, time);
    if (ret != 2)
    {
        printf("Invalid time format\n");
        return;
    }

    lv_obj_t *main_windows = lv_scr_act(); // 获取当前屏幕

    // 创建标签用于显示日期
    lv_obj_t *label_date = lv_label_create(main_windows);
    lv_label_set_text(
        label_date,
        date);
    lv_obj_set_style_text_font(label_date, &lv_font_simsun_16_cjk, 0);
    lv_obj_set_style_border_color(label_date, lv_color_hex(0x000000), LV_PART_MAIN);
    lv_obj_set_pos(label_date, 115, 10);
    lv_obj_set_width(label_date, 100);

    // 创建标签用于显示时间
    lv_obj_t *label_time = lv_label_create(main_windows);
    lv_label_set_text(
        label_time,
        time);
    lv_obj_set_style_text_font(label_time, &lv_font_simsun_16_cjk, 0);
    lv_obj_set_style_border_color(label_time, lv_color_hex(0x000000), LV_PART_MAIN);
    lv_obj_set_pos(label_time, 120, 30);
    lv_obj_set_width(label_time, 100);

    // 使用 sscanf 从 time 中提取时、分、秒信息
    sscanf(time, "%d:%d:%d", &hours, &minutes, &seconds);

    // 创建一个定时器每秒更新时间
    lv_timer_t *timer = lv_timer_create(time_update_cb, 1000, label_time);
}
// 每秒更新时间
void time_update_cb(lv_timer_t *timer)
{
    // 获取标签对象，这里假设在创建定时器时已经将标签对象作为 user_data 传递
    lv_obj_t *label_time = (lv_obj_t *)timer->user_data;

    // 每秒加一
    seconds++;
    if (seconds >= 60)
    {
        seconds = 0;
        minutes++;
        if (minutes >= 60)
        {
            minutes = 0;
            hours++;
            if (hours >= 24)
            {
                hours = 0;
            }
        }
    }

    // 格式化新的时间字符串
    char time_msg[64];
    sprintf(time_msg, "%02d:%02d:%02d", hours, minutes, seconds);

    // 更新标签文本
    lv_label_set_text(label_time, time_msg);
}

// 显示天气标签
void weather_label(char *weather_msg)
{
    LV_FONT_DECLARE(lv_font_HeiTi_Light_16_cjk);

    lv_obj_t *main_windows = lv_scr_act(); // 获取当前屏幕

    char weather[256];
    char weather_text[276];
    char temp[256];
    char temp_text[276];
    // 使用 sscanf 从 msg 中提取天气和温度信息
    int ret = sscanf(weather_msg, "Weather: %255[^,], Temp: %255[^C]", weather, temp);
    if (ret == 2)
    {
        // printf("Weather: %s, Temp: %s\n", weather, temp);
    }
    else
    {
        perror("sscanf failed");
    }
    sprintf(weather_text, "当前天气: %s", weather);
    sprintf(temp_text, "当前温度: %sC", temp);

    // 创建标签用于显示天气和温度信息
    lv_obj_t *label_1 = lv_label_create(main_windows);
    lv_label_set_text(
        label_1,
        weather_text);
    lv_obj_set_style_text_font(label_1, &lv_font_HeiTi_Light_16_cjk, 0);
    lv_obj_set_style_border_color(label_1, lv_color_hex(0x000000), LV_PART_MAIN);
    lv_obj_set_pos(label_1, 670, 10);
    lv_obj_set_width(label_1, 130);

    lv_obj_t *label_2 = lv_label_create(main_windows);
    lv_label_set_text(
        label_2,
        temp_text);
    lv_obj_set_style_text_font(label_2, &lv_font_HeiTi_Light_16_cjk, 0);
    lv_obj_set_style_border_color(label_2, lv_color_hex(0x000000), LV_PART_MAIN);
    lv_obj_set_pos(label_2, 670, 30);
    lv_obj_set_width(label_2, 130);

    lv_scr_load(main_windows);
}

// 更新聊天列表
void update_online_clients(IpList ipList)
{
    IpNode *current = ipList;
    if (online_clients_list == NULL)
    {
        // 如果列表不存在，则创建一个新的列表
        online_clients_list = lv_list_create(lv_scr_act());
        lv_obj_set_size(online_clients_list, 181, 371);
        lv_obj_set_style_radius(online_clients_list, 0, LV_PART_MAIN);
        lv_obj_set_pos(online_clients_list, 76, 108);
    }
    else
    {
        // 如果列表已存在，清空现有列表
        lv_obj_clean(online_clients_list);
    }
    lv_obj_t *list_item;
    if (strlen(current->ip) > 0)
    {
        // 群聊列表项
        list_item = lv_list_add_btn(online_clients_list, LV_SYMBOL_WIFI, "GROUP_CHAT");
        lv_obj_set_width(list_item, 170);
        lv_obj_add_event_cb(list_item, online_client_event_cb, LV_EVENT_CLICKED, "GROUP");
    }
    else
        return;

    // 遍历链表并添加每个在线客户端的 IP 到列表
    while (current != NULL)
    {
        if (strlen(current->ip) > 0) // 排除空字符串
        {
            // 创建列表项
            list_item = lv_list_add_btn(online_clients_list, LV_SYMBOL_WIFI, current->ip);
            lv_obj_set_width(list_item, 170);
            // 设置列表项的事件回调
            lv_obj_add_event_cb(list_item, online_client_event_cb, LV_EVENT_CLICKED, current->ip);
        }
        // 移动到下一个节点
        current = current->next;
    }
}

// 事件处理函数，当点击列表项时调用
void online_client_event_cb(lv_event_t *e)
{
    LV_FONT_DECLARE(lv_font_HeiTi_Light_16_cjk);

    const char *btn_text = (const char *)lv_event_get_user_data(e);

    if (group_label == NULL || private_label == NULL)
        chat_label_init();

    static const char *btns[] = {NULL}; // 提示框按钮
    // 当未关闭当前聊天窗口直接点击其他聊天项时提示
    if (mode != 0)
    {
        prompt_msgbox("请先关闭当前聊天窗口!");
    }
    else if (btn_text == "GROUP")
    {
        chat_window();
        lv_obj_clear_flag(group_label, LV_OBJ_FLAG_HIDDEN);
        if (group_chat_canvas != NULL)
            lv_obj_clear_flag(group_chat_canvas, LV_OBJ_FLAG_HIDDEN);
        mode = 2; // 群聊
    }
    else
    {
        chat_window();
        lv_obj_clear_flag(private_label, LV_OBJ_FLAG_HIDDEN);
        if (private_chat_canvas != NULL)
            lv_obj_clear_flag(private_chat_canvas, LV_OBJ_FLAG_HIDDEN);
        mode = 1; // 私聊
        memset(target_ip, 0, sizeof(target_ip));
        strcpy(target_ip, btn_text);
        // show_private_msg("开始聊天", btn_text);
    }
}

// 初始化聊天标签
void chat_label_init()
{
    LV_FONT_DECLARE(lv_font_HeiTi_Light_16_cjk);

    group_label = lv_label_create(lv_scr_act());
    lv_label_set_text(group_label, "群聊");
    lv_obj_set_pos(group_label, 470, 72);
    lv_obj_set_style_text_font(group_label, &lv_font_HeiTi_Light_16_cjk, 0);
    lv_obj_set_style_border_color(group_label, lv_color_hex(0x000000), LV_PART_MAIN);
    if (group_label != NULL)
        lv_obj_add_flag(group_label, LV_OBJ_FLAG_HIDDEN);

    private_label = lv_label_create(lv_scr_act());
    lv_label_set_text(private_label, "私聊");
    lv_obj_set_pos(private_label, 470, 72);
    lv_obj_set_style_text_font(private_label, &lv_font_HeiTi_Light_16_cjk, 0);
    lv_obj_set_style_border_color(private_label, lv_color_hex(0x000000), LV_PART_MAIN);
    if (private_label != NULL)
        lv_obj_add_flag(private_label, LV_OBJ_FLAG_HIDDEN);
}

// 创建聊天窗口
void chat_window()
{
    // 初次调用时创建，之后调用时复用
    if (text_ta == NULL)
    {
        // 创建一个输入框
        text_ta = lv_textarea_create(lv_scr_act());
        lv_textarea_set_text(text_ta, "");
        lv_textarea_set_one_line(text_ta, true); // 单行
        lv_obj_set_width(text_ta, 377);          // 宽度
        lv_obj_set_height(text_ta, 60);          // 高度
        lv_obj_set_pos(text_ta, 333, 405);
        lv_obj_add_event_cb(text_ta, ta_event_cb, LV_EVENT_ALL, NULL);

        LV_FONT_DECLARE(lv_font_HeiTi_Light_16_cjk);

        text_label = lv_label_create(lv_scr_act());
        lv_label_set_text(text_label, "请输入 :");
        lv_obj_set_style_text_font(text_label, &lv_font_HeiTi_Light_16_cjk, 0);
        lv_obj_align_to(text_label, text_ta, LV_ALIGN_OUT_LEFT_MID, 0, 0);

        // 创建一个键盘
        kb = lv_keyboard_create(lv_scr_act());
        lv_obj_set_size(kb, LV_HOR_RES, LV_VER_RES / 2);
        lv_obj_add_event_cb(kb, ta_event_cb, LV_EVENT_ALL, NULL); // 为键盘添加事件回调
        if (kb != NULL)
            lv_obj_add_flag(kb, LV_OBJ_FLAG_HIDDEN); // 初始时隐藏键盘

        // 关闭按钮
        close_btn = lv_btn_create(lv_scr_act());
        lv_obj_set_size(close_btn, 30, 30);
        lv_obj_set_pos(close_btn, 760, 65);
        lv_obj_set_style_bg_color(close_btn, lv_color_hex(0xFF0000), LV_PART_MAIN);
        lv_obj_add_event_cb(close_btn, close_btn_cb, LV_EVENT_CLICKED, "CLOSE");

        lv_obj_t *label_obj = lv_label_create(close_btn);
        lv_label_set_text(label_obj, LV_SYMBOL_CLOSE);
        lv_obj_set_style_text_color(label_obj, lv_color_hex(0x000000), LV_PART_MAIN);
        lv_obj_center(label_obj);
    }
    else // 显示隐藏的控件
    {
        lv_obj_clear_flag(text_ta, LV_OBJ_FLAG_HIDDEN);
        lv_obj_clear_flag(text_label, LV_OBJ_FLAG_HIDDEN);
        lv_obj_clear_flag(close_btn, LV_OBJ_FLAG_HIDDEN);
    }
}
// 输入框事件回调函数
void ta_event_cb(lv_event_t *e)
{
    lv_event_code_t code = lv_event_get_code(e);
    lv_obj_t *ta = lv_event_get_target(e);
    if (code == LV_EVENT_FOCUSED) // 获得焦点
    {
        lv_keyboard_set_textarea(kb, ta);          // 将键盘与输入框关联
        lv_obj_clear_flag(kb, LV_OBJ_FLAG_HIDDEN); // 显示键盘

        // 计算新的位置，使得文本框、标签和上传图标一起移动
        lv_coord_t kb_height = lv_obj_get_height(kb);
        lv_coord_t new_y = lv_obj_get_y(ta) - kb_height + 10;

        // 移动文本框到新位置
        lv_obj_set_y(ta, new_y);
        lv_obj_align_to(text_label, ta, LV_ALIGN_OUT_LEFT_MID, 0, 0);

        // 设置聊天画布的高度以及滚动到最新
        if (private_chat_canvas != NULL && chat_mode == 2)
        {
            lv_obj_set_height(private_chat_canvas, 80);
            lv_obj_scroll_to_y(private_chat_canvas, private_msg_cont * 40, LV_ANIM_ON);
        }
        else if (group_chat_canvas != NULL && chat_mode == 1)
        {
            lv_obj_set_height(group_chat_canvas, 80);
            lv_obj_scroll_to_y(group_chat_canvas, group_msg_cont * 40, LV_ANIM_ON);
        }
    }
    else if (code == LV_EVENT_DEFOCUSED) // 失去焦点
    {
        lv_keyboard_set_textarea(kb, NULL);
        if (kb != NULL)
            lv_obj_add_flag(kb, LV_OBJ_FLAG_HIDDEN);

        // 恢复文本框和标签的原始位置
        lv_obj_set_y(ta, 405);
        lv_obj_align_to(text_label, ta, LV_ALIGN_OUT_LEFT_MID, 0, 0);
        // 恢复聊天画布的高度
        if (private_chat_canvas != NULL && chat_mode == 2)
        {
            lv_obj_set_height(private_chat_canvas, 280);
        }
        else if (group_chat_canvas != NULL && chat_mode == 1)
        {
            lv_obj_set_height(group_chat_canvas, 280);
        }
    }

    if (code == LV_EVENT_READY && confirm_send != 1) // 点击确认键
    {
        if (chat_mode > 0 && strlen(input_text) > 0)
        {
            confirm_send = 1; // 确认发送
        }
    }
}

void close_btn_cb(lv_event_t *e)
{
    lv_obj_t *obj = lv_event_get_target(e);
    // const char *btn_text = lv_event_get_user_data(e);

    hide_chat_window();
}
// 将聊天窗口的控件隐藏
void hide_chat_window()
{
    if (text_ta != NULL)
        lv_obj_add_flag(text_ta, LV_OBJ_FLAG_HIDDEN);
    if (text_label != NULL)
        lv_obj_add_flag(text_label, LV_OBJ_FLAG_HIDDEN);
    if (close_btn != NULL)
        lv_obj_add_flag(close_btn, LV_OBJ_FLAG_HIDDEN);
    if (group_label != NULL)
        lv_obj_add_flag(group_label, LV_OBJ_FLAG_HIDDEN);
    if (private_label != NULL)
        lv_obj_add_flag(private_label, LV_OBJ_FLAG_HIDDEN);
    if (private_chat_canvas != NULL)
        lv_obj_add_flag(private_chat_canvas, LV_OBJ_FLAG_HIDDEN);
    if (group_chat_canvas != NULL)
        lv_obj_add_flag(group_chat_canvas, LV_OBJ_FLAG_HIDDEN);

    EXIT_SEND = 1;
}

// 显示私聊信息
void show_private_msg(const char *info)
{
    char show_msg[MSG_MAX_LEN];
    memset(show_msg, 0, MSG_MAX_LEN);
    strncpy(show_msg, info, MSG_MAX_LEN - 1);
    // printf("将显示消息%s\n", show_msg);

    lv_obj_t *main_windows = lv_scr_act(); // 获取当前屏幕

    // 创建或更新聊天画布
    if (private_chat_canvas == NULL)
    {
        private_chat_canvas = lv_obj_create(main_windows);
        if (!recv_flag)
            lv_obj_set_size(private_chat_canvas, 540, 80); // 设置画布大小
        else
            lv_obj_set_size(private_chat_canvas, 540, 280);
        lv_obj_set_pos(private_chat_canvas, 259, 95);                  // 设置画布位置
        lv_obj_set_style_radius(private_chat_canvas, 0, LV_PART_MAIN); // 圆角

        // 创建用户头像图片
        lv_obj_t *chat_info_img = lv_img_create(private_chat_canvas);
        lv_img_set_src(chat_info_img, "S:/mdata/project_2/res/img/default_head.png");
        lv_obj_align_to(chat_info_img, private_chat_canvas, LV_ALIGN_TOP_RIGHT, 0, 0);

        lv_obj_t *chat_info_img2 = lv_img_create(private_chat_canvas);
        lv_img_set_src(chat_info_img2, "S:/mdata/project_2/res/img/default_head.png");
        lv_obj_align_to(chat_info_img2, private_chat_canvas, LV_ALIGN_TOP_LEFT, 0, 0);

        // 创建用户标签
        lv_obj_t *my_label = lv_label_create(private_chat_canvas);
        lv_label_set_text(my_label, "My");
        lv_obj_set_style_text_font(my_label, &lv_font_simsun_16_cjk, 0);
        lv_obj_set_style_text_color(my_label, lv_color_hex(0x000000), LV_PART_MAIN);
        lv_obj_align_to(my_label, chat_info_img, LV_ALIGN_OUT_BOTTOM_MID, 0, 0); // 设置位置在头像下方

        lv_obj_t *he_label = lv_label_create(private_chat_canvas);
        lv_label_set_text(he_label, "He");
        lv_obj_set_style_text_font(he_label, &lv_font_simsun_16_cjk, 0);
        lv_obj_set_style_text_color(he_label, lv_color_hex(0x000000), LV_PART_MAIN);
        lv_obj_align_to(he_label, chat_info_img2, LV_ALIGN_OUT_BOTTOM_MID, 0, 0); // 设置位置在头像下方
    }

    if (private_msg_cont < MAX_MESSAGES)
    {
        // 不存在时创建私聊消息标签
        if (private_chat_labels[private_msg_cont] == NULL)
        {
            private_chat_labels[private_msg_cont] = lv_label_create(private_chat_canvas);
            if (private_chat_labels[private_msg_cont] == NULL)
            {
                perror("创建标签失败");
                return;
            }
            static lv_style_t style;
            lv_style_init(&style);                                                         // 初始化样式
            lv_style_set_border_color(&style, lv_color_hex(0x0000FF));                     // 设置边框颜色为蓝色
            lv_style_set_border_width(&style, 2);                                          // 设置边框宽度为2像素
            lv_obj_add_style(private_chat_labels[private_msg_cont], &style, LV_PART_MAIN); // 将样式应用到标签的主要内容部分
        }
        else // 存在时更新
        {
            lv_obj_clean(private_chat_labels[private_msg_cont]);
        }
        lv_label_set_text(private_chat_labels[private_msg_cont], show_msg);
        lv_obj_set_style_text_font(private_chat_labels[private_msg_cont], &lv_font_simsun_16_cjk, 0);
        lv_obj_set_style_border_color(private_chat_labels[private_msg_cont], lv_color_hex(0x0000FF), LV_PART_MAIN);
        if (!recv_flag)
            lv_obj_set_pos(private_chat_labels[private_msg_cont], 270, 10 + private_msg_cont * 40); // 每次消息间隔40像素
        else
            lv_obj_set_pos(private_chat_labels[private_msg_cont], 45, 10 + private_msg_cont * 40);
        lv_obj_set_width(private_chat_labels[private_msg_cont], 160);
        private_msg_cont++;
    }
    else // 如果消息达到最大数量，隐藏最早的消息
    {
        if (private_chat_labels[0] != NULL)
            lv_obj_add_flag(private_chat_labels[0], LV_OBJ_FLAG_HIDDEN);
        for (int i = 1; i < MAX_MESSAGES; i++)
        {
            private_chat_labels[i - 1] = private_chat_labels[i];
        }
        private_chat_labels[MAX_MESSAGES - 1] = lv_label_create(private_chat_canvas);
        lv_label_set_text(private_chat_labels[MAX_MESSAGES - 1], show_msg);
        static lv_style_t style;
        lv_style_init(&style);                                                         // 初始化样式
        lv_style_set_border_color(&style, lv_color_hex(0x0000FF));                     // 设置边框颜色为蓝色
        lv_style_set_border_width(&style, 2);                                          // 设置边框宽度为2像素
        lv_obj_add_style(private_chat_labels[private_msg_cont], &style, LV_PART_MAIN); // 将样式应用到标签的主要内容部分
        lv_obj_set_style_text_font(private_chat_labels[MAX_MESSAGES - 1], &lv_font_simsun_16_cjk, 0);
        lv_obj_set_style_border_color(private_chat_labels[MAX_MESSAGES - 1], lv_color_hex(0x000000), LV_PART_MAIN);
        if (!recv_flag)
            lv_obj_set_pos(private_chat_labels[MAX_MESSAGES - 1], 270, 10 + (MAX_MESSAGES - 1) * 40);
        else
            lv_obj_set_pos(private_chat_labels[MAX_MESSAGES - 1], 45, 10 + (MAX_MESSAGES - 1) * 40);
        lv_obj_set_width(private_chat_labels[MAX_MESSAGES - 1], 160);
        private_msg_cont = MAX_MESSAGES; // 重置消息计数
    }

    // 刷新聊天窗口
    lv_scr_load(main_windows);

    // 滚动到最新消息
    lv_obj_scroll_to_y(private_chat_canvas, private_msg_cont * 40, LV_ANIM_ON);
    recv_flag = 0;
    printf("成功显示信息\n");
}

// 显示群聊信息
void show_group_msg(const char *info)
{
    char show_msg[MSG_MAX_LEN];
    memset(show_msg, 0, MSG_MAX_LEN);
    strncpy(show_msg, info, MSG_MAX_LEN - 1);
    // printf("将显示消息%s\n", show_msg);

    lv_obj_t *main_windows = lv_scr_act(); // 获取当前屏幕

    // 创建或更新聊天画布
    if (group_chat_canvas == NULL)
    {
        group_chat_canvas = lv_obj_create(main_windows);
        if (!recv_flag)
            lv_obj_set_size(group_chat_canvas, 540, 80); // 设置画布大小
        else
            lv_obj_set_size(group_chat_canvas, 540, 280);
        lv_obj_set_pos(group_chat_canvas, 259, 95);                  // 设置画布位置
        lv_obj_set_style_radius(group_chat_canvas, 0, LV_PART_MAIN); // 圆角

        // 创建用户头像图片
        lv_obj_t *chat_info_img = lv_img_create(group_chat_canvas);
        lv_img_set_src(chat_info_img, "S:/mdata/project_2/res/img/default_head.png");
        lv_obj_align_to(chat_info_img, group_chat_canvas, LV_ALIGN_TOP_RIGHT, 0, 0);

        lv_obj_t *chat_info_img2 = lv_img_create(group_chat_canvas);
        lv_img_set_src(chat_info_img2, "S:/mdata/project_2/res/img/default_head.png");
        lv_obj_align_to(chat_info_img2, group_chat_canvas, LV_ALIGN_TOP_LEFT, 0, 0);

        // 创建用户标签
        lv_obj_t *my_label = lv_label_create(group_chat_canvas);
        lv_label_set_text(my_label, "My");
        lv_obj_set_style_text_font(my_label, &lv_font_simsun_16_cjk, 0);
        lv_obj_set_style_text_color(my_label, lv_color_hex(0x000000), LV_PART_MAIN);
        lv_obj_align_to(my_label, chat_info_img, LV_ALIGN_OUT_BOTTOM_MID, 0, 0); // 设置位置在头像下方

        lv_obj_t *other_label = lv_label_create(group_chat_canvas);
        lv_label_set_text(other_label, "other");
        lv_obj_set_style_text_font(other_label, &lv_font_simsun_16_cjk, 0);
        lv_obj_set_style_text_color(other_label, lv_color_hex(0x000000), LV_PART_MAIN);
        lv_obj_align_to(other_label, chat_info_img2, LV_ALIGN_OUT_BOTTOM_MID, 0, 0); // 设置位置在头像下方
    }

    // 创建或更新群聊消息标签
    if (group_msg_cont < MAX_MESSAGES)
    {
        if (group_chat_labels[group_msg_cont] == NULL)
        {
            group_chat_labels[group_msg_cont] = lv_label_create(group_chat_canvas);
            if (group_chat_labels[group_msg_cont] == NULL)
            {
                perror("创建标签失败");
                return;
            }
            static lv_style_t style;
            lv_style_init(&style);                                                     // 初始化样式
            lv_style_set_border_color(&style, lv_color_hex(0x0000FF));                 // 设置边框颜色为蓝色
            lv_style_set_border_width(&style, 2);                                      // 设置边框宽度为2像素
            lv_obj_add_style(group_chat_labels[group_msg_cont], &style, LV_PART_MAIN); // 将样式应用到标签的主要内容部分
        }
        else
        {
            lv_obj_clean(group_chat_labels[group_msg_cont]);
        }
        lv_label_set_text(group_chat_labels[group_msg_cont], show_msg);
        lv_obj_set_style_text_font(group_chat_labels[group_msg_cont], &lv_font_simsun_16_cjk, 0);
        lv_obj_set_style_border_color(group_chat_labels[group_msg_cont], lv_color_hex(0x0000FF), LV_PART_MAIN);
        if (!recv_flag)
            lv_obj_set_pos(group_chat_labels[group_msg_cont], 270, 10 + group_msg_cont * 40); // 每次消息间隔40像素
        else
            lv_obj_set_pos(group_chat_labels[group_msg_cont], 45, 10 + group_msg_cont * 40);
        lv_obj_set_width(group_chat_labels[group_msg_cont], 160);
        group_msg_cont++;
    }
    else // 如果消息达到最大数量，隐藏最早的消息
    {
        if (group_chat_labels[0] != NULL)
            lv_obj_add_flag(group_chat_labels[0], LV_OBJ_FLAG_HIDDEN);
        for (int i = 1; i < MAX_MESSAGES; i++)
        {
            group_chat_labels[i - 1] = group_chat_labels[i];
        }
        group_chat_labels[MAX_MESSAGES - 1] = lv_label_create(group_chat_canvas);
        lv_label_set_text(group_chat_labels[MAX_MESSAGES - 1], show_msg);
        static lv_style_t style;
        lv_style_init(&style);                                                     // 初始化样式
        lv_style_set_border_color(&style, lv_color_hex(0x0000FF));                 // 设置边框颜色为蓝色
        lv_style_set_border_width(&style, 2);                                      // 设置边框宽度为2像素
        lv_obj_add_style(group_chat_labels[group_msg_cont], &style, LV_PART_MAIN); // 将样式应用到标签的主要内容部分
        lv_obj_set_style_text_font(group_chat_labels[MAX_MESSAGES - 1], &lv_font_simsun_16_cjk, 0);
        lv_obj_set_style_border_color(group_chat_labels[MAX_MESSAGES - 1], lv_color_hex(0x0000FF), LV_PART_MAIN);
        if (!recv_flag)
            lv_obj_set_pos(group_chat_labels[MAX_MESSAGES - 1], 270, 10 + (MAX_MESSAGES - 1) * 40);
        else
            lv_obj_set_pos(group_chat_labels[MAX_MESSAGES - 1], 45, 10 + (MAX_MESSAGES - 1) * 40);
        lv_obj_set_width(group_chat_labels[MAX_MESSAGES - 1], 160);
        group_msg_cont = MAX_MESSAGES; // 重置消息计数
    }

    // 刷新聊天窗口
    lv_scr_load(main_windows);

    // 滚动到最新消息
    lv_obj_scroll_to_y(group_chat_canvas, group_msg_cont * 40, LV_ANIM_ON);
    recv_flag = 0;
    printf("成功显示信息\n");
}

// 客户端主程序
void *client(void *arg)
{
    // 创建套接字
    int cli_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (cli_fd == -1)
    {
        perror("socket ...");
        pthread_exit((void *)-1);
    }

    // 配置服务器网络信息的专属结构体变量
    struct sockaddr_in ser_inf;
    memset(&ser_inf, 0, sizeof(ser_inf));

    ser_inf.sin_family = AF_INET; // IPv4
    ser_inf.sin_port = htons(8888);
    ser_inf.sin_addr.s_addr = inet_addr("192.168.53.65"); // 服务器的IP地址

    // 连接服务器
    if (connect(cli_fd, (struct sockaddr *)&ser_inf, sizeof(ser_inf)) == -1)
    {
        perror("connect ...");
        connect_flag = 0;
        close(cli_fd);
        prompt_msgbox("连接服务器失败");
        return (void *)-1;
    }
    connect_flag = 1;
    prompt_msgbox("连接服务器成功,点击聊天列表可刷新聊天选项");
    printf("连接服务器成功\n");

    pthread_t recv_ser_id;
    if (pthread_create(&recv_ser_id, NULL, Recv_server, (void *)&cli_fd) != 0)
    {
        perror("pthread_create ...");
        return (void *)-1;
    }

    // 发送时间获取请求
    if (write(cli_fd, TIME_MASK, strlen(TIME_MASK) + 1) == -1)
    {
        perror("SEND TIME_MASK");
        return (void *)-1;
    }

    EXIT_CLIENT = 1;
    chat_mode = 0;
    char input[MSG_MAX_LEN];

    printf("》》》》》功能选择《《《《《\n");
    printf("1 私聊\n");
    printf("2 群聊\n");
    printf("3 天气\n");
    printf("4 在线\n");
    printf("5 退出\n");
    printf("》》》》》》》《《《《《《《\n");
    while (EXIT_CLIENT)
    {

        switch (mode)
        {
        case 1: // 私聊
            chat_mode = 2;
            PrivateChat_Task(&cli_fd);
            mode = 0;
            break;

        case 2: // 群聊
            chat_mode = 1;
            GroupChat_Task(&cli_fd);
            mode = 0;
            break;

        case 3: // 发送天气获取请求
            if (write(cli_fd, SHOW_WEATHER, strlen(SHOW_WEATHER) + 1) == -1)
            {
                perror("SEND SHOW_WEATHER");
                return (void *)-1;
            }
            mode = 0;
            break;

        case 4: // 发送在线获取请求
            if (write(cli_fd, SHOW_ONLINE_CLI, strlen(SHOW_ONLINE_CLI) + 1) == -1)
            {
                perror("write ...");
                return (void *)-1;
            }
            mode = 0;
            break;

        case 5:
            EXIT_CLIENT = 0;
            printf("退出\n");
            break;

        default:
            break;
        }
    }
    pthread_exit((void *)0);
}